// https://unocss.nodejs.cn/guide/config-file
import {
  defineConfig,
  presetAttributify,
  presetIcons,
  presetTypography,
  presetWind4,
  presetWebFonts,
  transformerDirectives,
  transformerVariantGroup,
} from 'unocss'
import fs from 'fs'
import path from 'path'
import { optimize } from 'svgo'
import { FileSystemIconLoader } from '@iconify/utils/lib/loader/node-loaders'
import { createExternalPackageIconLoader } from '@iconify/utils/lib/loader/external-pkg'

// 本地SVG图标目录
const iconsDir = './src/assets/icons'

/**
 * 自定义 SVGO 优化器，用于添加 fill 属性
 * @param svg SVG 字符串
 */
const svgOptimizer = (svg: string) => {
  const result = optimize(svg, {
    plugins: [
      // 使用自定义插件检查并条件性添加 fill 属性
      {
        name: 'customAddAttributes',
        fn: () => {
          return {
            element: {
              enter: (node) => {
                // 只处理 SVG 根元素
                if (node.name === 'svg') {
                  // 检查是否有 fill 属性
                  // 检查是否有 fill 属性或子元素有 fill 属性
                  const hasFillAttr = node.attributes.fill !== undefined
                  const hasChildrenWithFill = node.children.some(child =>
                    child.type === 'element' && child.attributes && child.attributes.fill !== undefined,
                  )

                  // 设置 aria-hidden
                  node.attributes['aria-hidden'] = 'true'

                  // 如果没有 fill 属性并且子元素也没有指定 fill，则添加 currentColor
                  if (!hasFillAttr && !hasChildrenWithFill) {
                    node.attributes.fill = 'currentColor'
                  }
                }
              },
            },
          }
        },
      },
      // 其他优化插件
      'removeXMLNS',
    ],
  })

  return result.data
}

/**
 * 判断文件是否为 SVG 文件
 * @param filePath 文件路径
 */
const isSvgFile = (filePath: string): boolean => {
  return filePath.endsWith('.svg') && fs.statSync(filePath).isFile()
}

/**
 * 处理嵌套的子目录图标集合
 */
const createNestedCollections = () => {
  const collections: Record<string, ReturnType<typeof FileSystemIconLoader>> = {}
  const safeList: string[] = []

  // 添加根目录图标集合
  collections['svg'] = FileSystemIconLoader(iconsDir, svgOptimizer)

  // 处理目录函数
  const processDirectory = (dir: string, collectionPrefix = '') => {
    let entries: fs.Dirent[] = []

    try {
      entries = fs.readdirSync(dir, { withFileTypes: true })
    } catch (error) {
      console.error(`无法读取目录 ${dir}:`, error)
      return
    }

    // 先处理当前目录的SVG文件
    const svgFiles = entries
      .filter(entry => !entry.isDirectory() && entry.name.endsWith('.svg'))
      .map(entry => entry.name)

    // 添加到safeList
    const prefix = collectionPrefix ? `svg-${collectionPrefix}` : 'svg'
    svgFiles.forEach(file => {
      safeList.push(`i-${prefix}:${file.replace('.svg', '')}`)
    })

    // 处理子目录
    const subDirectories = entries.filter(entry => entry.isDirectory())

    for (const subDir of subDirectories) {
      const subDirPath = path.join(dir, subDir.name)
      const newPrefix = collectionPrefix ? `${collectionPrefix}-${subDir.name}` : subDir.name

      // 为子目录创建图标集合
      collections[`svg-${newPrefix}`] = FileSystemIconLoader(subDirPath, svgOptimizer)

      // 递归处理子目录
      processDirectory(subDirPath, newPrefix)
    }
  }

  // 处理根目录SVG文件
  try {
    const rootFiles = fs.readdirSync(iconsDir)
    const rootSvgFiles = rootFiles
      .filter(file => isSvgFile(path.join(iconsDir, file)))

    rootSvgFiles.forEach(file => {
      safeList.push(`i-svg:${file.replace('.svg', '')}`)
    })
  } catch (error) {
    console.error('读取根目录图标失败:', error)
  }

  // 递归处理所有子目录
  processDirectory(iconsDir)

  return { collections, safeList }
}

/**
 * 创建图标集合和safeList
 */
const { collections: iconCollections, safeList: iconSafeList } = createNestedCollections()

/**
 * 图标集合
 */
export const collections = {
  ...iconCollections,
  ...createExternalPackageIconLoader('mdi'),
  ...createExternalPackageIconLoader('ep'),
  ...createExternalPackageIconLoader('ant-design'),
}

// @ts-ignore 同步版本 - 直接导入
import epIconsData from '@iconify-json/ep/icons.json' with { type: 'json' }

// 所有的 icon
const allIcons = [
  ...Object.keys(epIconsData.icons).map(name => `i-ep:${name}`),
]

/**
 * 安全列表
 */
export const safeList = [
  ...iconSafeList,
  ...allIcons,
]

/**
 * UnoCSS 配置文件
 * @see https://unocss.nodejs.cn/guide/config-file
 */
export default defineConfig({
  // 自定义快捷类
  shortcuts: {
    'wh-full': 'w-full h-full',
    'flex-center': 'flex justify-center items-center',
    'flex-x-center': 'flex justify-center',
    'flex-y-center': 'flex items-center',
    'flex-x-start': 'flex items-center justify-start',
    'flex-x-between': 'flex items-center justify-between',
    'flex-x-end': 'flex items-center justify-end',
  },
  theme: {
    colors: {
      primary: 'var(--el-color-primary)',
      primary_dark: 'var(--el-color-primary-light-5)',
    },
  },
  presets: [
    presetWind4(),
    presetAttributify(),
    presetIcons({
      // 额外属性
      extraProperties: {
        display: 'inline-block',
        width: '1em',
        height: '1em',
      },
      // 图表集合
      collections: collections,
      // 开启自动安装
      autoInstall: true,
    }),
    presetTypography(),
    presetWebFonts({
      fonts: {
        // ...
      },
    }),
  ],
  safelist: safeList,
  transformers: [
    transformerDirectives(),
    transformerVariantGroup(),
  ],
})
